<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <!-- 项目基本信息 -->
      <el-card class="box-card">
        <div slot="header">
          <div class="card-header">
            <span>项目基本信息</span>
            <el-button
              v-if="!isView && !form.projectId"
              style="float: right; padding: 3px 0"
              type="text"
              @click="handleSelectProject"
            >选择项目</el-button>
          </div>
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="form.contractName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="enterpriseName">
              <el-input v-model="form.enterpriseName" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目编号" prop="projectNumber">
              <el-input v-model="form.projectNumber" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实施方式">
              <el-input v-model="form.embodimentLabel" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目负责人" prop="projectLeader">
              <el-input v-model="form.projectLeader" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划时间" prop="plannedTime">
              <el-input
                v-model="form.plannedTimeLabel"
                readonly
                placeholder="开始日期 至 结束日期"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 项目组成员 -->
      <el-card class="box-card">
        <div slot="header">
          <div class="card-header">
            <span>项目组成员</span>
            <el-button
              v-if="!isView"
              style="float: right; padding: 3px 0"
              type="text"
              @click="handleAddMember"
            >新增</el-button>
          </div>
        </div>
        <el-table :data="form.members" border>
          <el-table-column label="成员姓名" prop="memberName" align="center" />
          <el-table-column label="联系方式" prop="contactInfo" align="center" />
          <el-table-column label="职位" prop="position" align="center" />
          <el-table-column v-if="!isView" label="操作" align="center" width="100">
            <template slot-scope="scope">
              <el-button type="text" @click="handleDeleteMember(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 实施工艺 -->
      <el-card class="box-card">
        <div slot="header">
          <div class="card-header">
            <span>实施工艺</span>
            <el-button
              v-if="!isView"
              style="float: right; padding: 3px 0"
              type="text"
              @click="handleAddProcess"
            >新增</el-button>
          </div>
        </div>
        <el-table
          ref="processTable"
          :data="form.processes"
          border
          row-key="processStageId"
          class="draggable-table"
        >
          <el-table-column label="序号" align="center" width="50">
            <template slot-scope="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="阶段名称" prop="processStageName" align="center">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.processStageName"
                placeholder="请输入阶段名称"
                :disabled="isView"
              />
            </template>
          </el-table-column>
          <el-table-column label="计划开始时间" align="center">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.plannedStartTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                :disabled="isView"
              />
            </template>
          </el-table-column>
          <el-table-column label="计划完成时间" align="center">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.plannedEndTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                :disabled="isView"
              />
            </template>
          </el-table-column>
          <el-table-column label="执行人" align="center">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.executorPersonId"
                placeholder="请选择执行人"
                :disabled="isView"
              >
                <el-option
                  v-for="member in form.members"
                  :key="member.userId"
                  :label="member.memberName"
                  :value="member.userId"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="应收款项" align="center">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.receivableAmount"
                placeholder="请输入金额"
                :disabled="isView"
              />
            </template>
          </el-table-column>
          <el-table-column v-if="!isView" label="操作" align="center" width="100">
            <template slot-scope="scope">
              <el-button type="text" @click="handleDeleteProcess(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
          <el-table-column type="expand" label="交付物" width="100">
            <template slot-scope="scope">
              <div class="deliverable-container">
                <div class="deliverable-header" v-if="!isView">
                  <el-button
                    type="text"
                    @click="handleAddDeliverable(scope.row)"
                  >新增</el-button>
                </div>
                <el-table
                  :data="scope.row.deliverables"
                  border
                  class="sub-table"
                >
                  <el-table-column label="交付物名称" align="center">
                    <template slot-scope="props">
                      <el-input
                        v-model="props.row.deliverableName"
                        placeholder="请输入交付物名称"
                        :disabled="isView"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="是否必须" align="center" width="120">
                    <template slot-scope="props">
                      <el-select
                        v-model="props.row.isRequired"
                        placeholder="请选择"
                        :disabled="isView"
                      >
                        <el-option label="是" value="1" />
                        <el-option label="否" value="0" />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column v-if="!isView" label="操作" align="center" width="100">
                    <template slot-scope="props">
                      <el-button
                        type="text"
                        @click="handleDeleteDeliverable(scope.row, props.$index)"
                      >删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 费用预算 -->
      <el-card class="box-card">
        <div slot="header">
          <div class="card-header">
            <span>费用预算</span>
            <el-button
              v-if="!isView"
              style="float: right; padding: 3px 0"
              type="text"
              @click="handleAddBudget"
            >新增</el-button>
          </div>
        </div>
        <el-table :data="form.budgets" border>
          <el-table-column label="费用说明" align="center">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.costDescription"
                placeholder="请输入费用说明"
                :disabled="isView"
              />
            </template>
          </el-table-column>
          <el-table-column label="费用类型" align="center">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.costType"
                placeholder="请选择费用类型"
                :disabled="isView"
              >
                <el-option
                  v-for="dict in dict.type.budget_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="金额(元)" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.amount"
                :min="0"
                :precision="2"
                :step="100"
                :disabled="isView"
                placeholder="请输入金额"
              />
            </template>
          </el-table-column>
          <el-table-column label="工艺阶段" align="center">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.processStage"
                placeholder="请选择工艺阶段"
                :disabled="isView"
              >
                <el-option
                  v-for="process in form.processes"
                  :key="process.processStageId"
                  :label="process.processStageName"
                  :value="process.processStageName"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column v-if="!isView" label="操作" align="center" width="100">
            <template slot-scope="scope">
              <el-button type="text" @click="handleDeleteBudget(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 底部按钮 -->
      <div class="bottom-buttons">
        <template v-if="!isView">
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button type="primary" @click="submitAndAudit">提交</el-button>
        </template>
        <el-button @click="cancel">返回</el-button>
      </div>
    </el-form>

    <!-- 选择项目组件 -->
    <select-project ref="selectProject" @select="handleProjectSelect" />

    <!-- 添加成员选择对话框 -->
    <select-member
      ref="selectMember"
      :selected-members="form.members"
      @select="handleMemberSelect"
    />
  </div>
</template>

<script>
import { getProjectInfo, getProcessTemplate, getProjectPlanning, addProjectPlanning, updateProjectPlanning, submitForApproval } from '@/api/project/planning'
import Sortable from 'sortablejs'
import SelectMember from './components/selectmember.vue'
import SelectProject from './components/selectproject.vue'

export default {
  name: 'ProjectPlanningForm',
  props: {
    // 操作类型：add/edit/view
    opt: {
      type: String,
      required: true
    },
    // 策划ID
    id: {
      type: String,
      default: null
    }
  },
  components: {
    SelectMember,
    SelectProject
  },
  data() {
    return {
      // 表单参数
      form: {
        planningId: undefined,
        projectId: undefined,
        contractName: undefined,
        enterpriseName: undefined,
        projectNumber: undefined,
        projectName: undefined,
        productName: undefined,
        embodiment: undefined,
        projectLeader: undefined,
        plannedTime: [],
        members: [],
        processes: [],
        budgets: []
      },
      // 表单校验规则
      rules: {
        plannedTime: [
          { required: true, message: '请选择计划时间', trigger: 'change' }
        ]
      },
      // 页面状态
      isView: false
    }
  },
  created() {
    // 根据操作类型判断页面模式
    this.isView = this.opt === 'view'

    if (this.id) {
      // 获取项目策划详情
      this.getDetail(this.id)
    }
  },
  mounted() {
    this.rowDrop()
  },
  methods: {
    /** 获取项目策划详情 */
    getDetail(id) {
      // useType: 1-策划, 2-模版, 3-实施
      const useType = 1

      getProjectPlanning(id, useType).then(response => {
        const data = response.data

        // 处理后端返回的执行人数据和交付物数据
        if (data.processes) {
          data.processes = data.processes.map(process => ({
            ...process,
            executorPersonId: process.executorPerson,
            executorPerson: undefined,
            deliverables: process.deliverables ? process.deliverables.map(item => ({
              ...item,
              isRequired: item.isRequired.toString() // 将数字转换为字符串
            })) : []
          }))
        }

        // 处理预算数据
        if (data.budgets) {
          data.budgets = data.budgets.map(budget => ({
            ...budget,
            costDescription: budget.costDescription
          }))
        }

        // 处理实施方式的标签
        const embodimentDict = this.dict.type.project_embodiment.find(d => d.value === data.embodiment)
        const embodimentLabel = embodimentDict ? embodimentDict.label : ''

        this.form = {
          ...data,
          // 设置计划时间
          plannedTime: [data.plannedStartTime, data.plannedEndTime],
          plannedTimeLabel: data.plannedStartTime && data.plannedEndTime ?
            `${data.plannedStartTime} 至 ${data.plannedEndTime}` : '',
          // 设置实施方式
          embodiment: data.embodiment,
          embodimentLabel: embodimentLabel,
          members: data.members || [],
          processes: data.processes || [],
          budgets: data.budgets || []
        }
      })
    },
    /** 表单提交 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const data = {
            ...this.form,
            plannedStartTime: this.form.plannedTime[0],
            plannedEndTime: this.form.plannedTime[1],
            processes: this.form.processes.map(process => ({
              processId: process.processId,
              planningId: this.form.planningId,
              processTemplateId: process.processTemplateId,
              processStageId: process.processStageId,
              processStageName: process.processStageName,
              processStageOrder: process.processStageOrder,
              plannedStartTime: process.plannedStartTime,
              plannedEndTime: process.plannedEndTime,
              executorPerson: process.executorPersonId,
              receivableAmount: process.receivableAmount,
              useType: 1,
              deliverables: process.deliverables ? process.deliverables.map(item => ({
                deliverableId: item.deliverableId,
                processId: process.processId,
                deliverableName: item.deliverableName,
                deliverableOrder: item.deliverableOrder,
                isRequired: parseInt(item.isRequired),
                useType: 1
              })) : []
            }))
          }

          if (this.opt === 'edit') {
            updateProjectPlanning(data).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.cancel()
            })
          } else {
            addProjectPlanning(data).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.cancel()
            })
          }
        }
      })
    },
    /** 提交并审核 */
    submitAndAudit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 准备表单数据
          const formData = {
            ...this.form,
            plannedStartTime: this.form.plannedTime[0],
            plannedEndTime: this.form.plannedTime[1],
            processes: this.form.processes.map(process => ({
              ...process,
              executorPerson: process.executorPersonId,
              executorPersonId: undefined,
              deliverables: process.deliverables ? process.deliverables.map(item => ({
                ...item,
                isRequired: parseInt(item.isRequired),
                useType: 1
              })) : []
            }))
          }

          // 调用后端接口提交审核
          submitForApproval(formData).then(response => {
            this.$modal.msgSuccess('提交成功')
            this.cancel()
          }).catch(error => {
            this.$modal.msgError('提交失败：' + error.message)
          })
        }
      })
    },
    /** 打开选择项目对话框 */
    handleSelectProject() {
      this.$refs.selectProject.show()
    },
    /** 选择项目回调 */
    handleProjectSelect(project) {
      // 回显项目信息
      this.form.projectId = project.projectId
      this.form.contractName = project.contractName
      this.form.enterpriseName = project.enterpriseName
      this.form.projectNumber = project.projectNumber
      this.form.projectName = project.projectName
      this.form.productName = project.productName
      // 设置实施方式的标签
      const embodimentDict = this.dict.type.project_embodiment.find(d => d.value === project.embodiment)
      this.form.embodiment = project.embodiment
      this.form.embodimentLabel = embodimentDict ? embodimentDict.label : ''
      this.form.projectLeader = project.projectLeader
      // 设置计划时间的显示
      this.form.plannedTime = [project.plannedStartTime, project.plannedEndTime]
      this.form.plannedTimeLabel = project.plannedStartTime && project.plannedEndTime ?
        `${project.plannedStartTime} 至 ${project.plannedEndTime}` : ''

      // 获取工艺模板
      getProcessTemplate(project.productId).then(response => {
        const template = response.data[0]
        if (template && template.processVOS) {
          this.form.processes = template.processVOS.map(process => {
            const newProcessId = this.guid()
            return {
              processId: newProcessId,
              processTemplateId: template.id,
              processStageId: process.processStageId,
              processStageName: process.processStageName,
              processStageOrder: process.processStageOrder,
              plannedStartTime: '',
              plannedEndTime: '',
              executorPersonId: '',
              receivableAmount: '',
              deliverables: process.deliverables ? process.deliverables.map(item => ({
                deliverableId: this.guid(),
                processId: newProcessId,
                deliverableName: item.deliverableName,
                isRequired: item.isRequired ? item.isRequired.toString() : '0',
                deliverableOrder: item.deliverableOrder || 1,
                deliveryTime: null,
                deliveryPerson: null,
                useType: 1
              })) : []
            }
          })
        }
      })
    },
    // 其他方法...
    handleAddMember() {
      this.$refs.selectMember.show()
    },
    handleDeleteMember(index) {
      const member = this.form.members[index]
      // 检查是否有工艺使用该成员作为执行人
      const usedProcesses = this.form.processes.filter(p => p.executorPersonId === member.userId)

      if (usedProcesses.length > 0) {
        this.$modal.confirm(
          `该成员已被指定为${usedProcesses.length}个工艺阶段的执行人，删除后相关工艺的执行人将被清空，是否继续？`,
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          // 清空相关工艺的执行人
          usedProcesses.forEach(process => {
            process.executorPersonId = ''
          })
          // 删除成员
          this.form.members.splice(index, 1)
        }).catch(() => {})
      } else {
        // 如果没有使用该成员，直接删除
        this.form.members.splice(index, 1)
      }
    },
    handleAddProcess() {
      this.form.processes.push({
        processId: this.guid(),
        processStageId: this.guid(),
        processStageName: '',
        processStageOrder: this.form.processes.length + 1,
        plannedStartTime: '',
        plannedEndTime: '',
        executorPersonId: '',
        receivableAmount: '',
        deliverables: []
      })
    },
    handleDeleteProcess(index) {
      this.form.processes.splice(index, 1)
    },
    handleManageDeliverable(row) {

    },
    handleAddBudget() {
      this.form.budgets.push({
        budgetId: this.guid(),
        costDescription: '',
        costType: undefined,
        amount: undefined,
        processStage: '',
        useType: 1
      })
    },
    handleDeleteBudget(index) {
      this.$modal.confirm('是否确认删除该预算项？').then(() => {
        this.form.budgets.splice(index, 1)
      }).catch(() => {})
    },
    cancel() {
      // 通知父组件关闭表单
      this.$emit('change')
    },
    /** 实现表格拖拽排序 */
    rowDrop() {
      const tbody = this.$refs.processTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(tbody, {
        handle: '.el-table__row',
        animation: 300,
        onEnd: ({ newIndex, oldIndex }) => {
          const currRow = this.form.processes.splice(oldIndex, 1)[0]
          this.form.processes.splice(newIndex, 0, currRow)

          // 更新排序号
          this.form.processes = this.form.processes.map((item, index) => ({
            ...item,
            processStageOrder: index + 1
          }))
        }
      })
    },
    /** 选择成员回调 */
    handleMemberSelect(members) {
      const oldMembers = this.form.members
      // 直接替换成员列表
      this.form.members = members

      // 处理实施工艺中的执行人
      this.handleProcessExecutorChange(oldMembers, members)

      this.$modal.msgSuccess('添加成员成功')
    },

    /** 处理成员变更后的执行人 */
    handleProcessExecutorChange(oldMembers, newMembers) {
      // 构建新成员的ID集合，用于快速查找
      const newMemberIds = new Set(newMembers.map(m => m.userId))
      // 构建成员ID到名称的映射，用于提示信息
      const memberNames = new Map(newMembers.map(m => [m.userId, m.memberName]))

      // 遍历所有工艺
      this.form.processes.forEach(process => {
        // 如果执行人不为空，且不在新成员列表中
        if (process.executorPersonId && !newMemberIds.has(process.executorPersonId)) {
          const executorName = oldMembers.find(m => m.userId === process.executorPersonId)?.memberName || '未知'
          // 清空执行人
          process.executorPersonId = ''
          // 提示信息
          this.$modal.msgWarning(`工艺"${process.processStageName}"的执行人"${executorName}"已被移除`)
        }
      })
    },
    /** 生成UUID */
    guid() {
      function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
      }
      return (S4() + S4() + "-" + S4() + "-" + S4() + S4() + S4())
    },
    /** 处理工艺阶段变更 */
    handleProcessChange() {
      // 当工艺阶段被删除时，清空相关预算的工艺阶段
      const stageNames = new Set(this.form.processes.map(p => p.processStageName))
      this.form.budgets.forEach(budget => {
        if (budget.processStage && !stageNames.has(budget.processStage)) {
          budget.processStage = ''
          this.$modal.msgWarning('由于工艺阶段变更，部分预算的工艺阶段已被清空')
        }
      })
    },
    /** 添加交付物 */
    handleAddDeliverable(process) {
      if (!process.deliverables) {
        process.deliverables = []
      }
      process.deliverables.push({
        deliverableId: this.guid(),
        processId: process.processId,
        deliverableName: '',
        isRequired: '0',
        deliverableOrder: process.deliverables.length + 1,
        deliveryTime: null,
        deliveryPerson: null,
        useType: 1
      })
    },

    /** 删除交付物 */
    handleDeleteDeliverable(process, index) {
      this.$modal.confirm('是否确认删除该交付物？').then(() => {
        process.deliverables.splice(index, 1)
      }).catch(() => {})
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getProjectList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    }
  },
  beforeDestroy() {
    if (this.sortable) {
      this.sortable.destroy()
    }
  },
  dicts: ['project_embodiment', 'budget_type'],
  watch: {
    // 监听工艺变更
    'form.processes': {
      handler: 'handleProcessChange',
      deep: true
    }
  }
}
</script>

<style>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.card-header span {
  font-size: 14px;
  font-weight: bold;
}
/* 调整表格中输入框和选择器的样式 */
.el-table .el-input-number {
  width: 100%;
}
.el-table .el-input-number .el-input__inner {
  text-align: center;
}
.el-table .el-select {
  width: 100%;
}
/* 调整子表格样式 */
.sub-table {
  margin: 10px 40px;
}
.el-table__expanded-cell {
  padding: 10px !important;
}
/* 交付物容器样式 */
.deliverable-container {
  padding: 10px 20px;
}
.deliverable-header {
  margin-bottom: 10px;
  text-align: right;
}
/* 调整子表格中输入框和选择器的样式 */
.sub-table .el-input,
.sub-table .el-select {
  width: 100%;
}
/* 调整展开单元格的样式 */
.el-table__expanded-cell {
  padding: 10px !important;
}
</style>

<style scoped>
.app-container {
  padding: 20px;
}
.box-card {
  margin-bottom: 20px;
}
.bottom-buttons {
  margin-top: 20px;
  text-align: center;
}
/* 添加拖拽样式 */
.draggable-table >>> .el-table__row {
  cursor: move;
}
.draggable-table >>> .el-table__row:hover {
  background-color: #f5f7fa;
}
.sortable-ghost {
  opacity: 0.8;
  color: #fff;
  background: #409eff !important;
}
/* 调整选择器在表格中的样式 */
.el-table .el-select {
  width: 100%;
}
</style>
